<?php

namespace plugin\admin\app\controller;

use plugin\admin\app\common\Auth;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\StoreCategory;
use support\Request;
use support\Response;
use plugin\admin\app\model\Store;
use plugin\admin\app\controller\Crud;
use support\exception\BusinessException;

/**
 * 商行管理 
 */
class StoreController extends Crud
{
    
    /**
     * @var Store
     */
    protected $model = null;

    /**
     * 构造函数
     * @return void
     */
    public function __construct()
    {
        $this->model = new Store;
    }
    
    /**
     * 浏览
     * @return Response
     */
    public function index(): Response
    {
        return view('store/index');
    }

    protected function insertInput(Request $request): array
    {
        $data = $request->post();
//        if ($data['title']) {
//            $content = [];
//            foreach ($data['title'] as $key=>$value) {
//                if ($key && $value) {
//                    $content[] = [
//                        'title' => $value,
//                        'content' => $data['content'][$key]
//                    ];
//                }
//            }
//
//            $content = json_encode($content, JSON_UNESCAPED_UNICODE);
//
//            $data['content'] = $content;
//        }

        $data = $this->inputFilter($data);


        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            $data[$password_filed] = Util::passwordHash($data[$password_filed]);
        }

        if (!Auth::isSupperAdmin() && $this->dataLimit) {
            if (!empty($data[$this->dataLimitField])) {
                $admin_id = $data[$this->dataLimitField];
                if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                    throw new BusinessException('无数据权限');
                }
            }
        }

        $data['created_time'] = date('Y-m-d H:i:s');


        return $data;
    }

    /**
     * 插入
     * @param Request $request
     * @return Response
     * @throws BusinessException
     */
    public function insert(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::insert($request);
        }
        return view('store/insert');
    }

    protected function updateInput(Request $request): array
    {
        $data = $request->post();
//        if ($data['title']) {
//            $content = [];
//            foreach ($data['title'] as $key=>$value) {
//                if ($value && $data['content'][$key]) {
//                    $content[] = [
//                        'title' => $value,
//                        'content' => $data['content'][$key]
//                    ];
//                }
//            }
//
//            $content = json_encode($content, JSON_UNESCAPED_UNICODE);
//
//            $data['content'] = $content;
//        }

        $primary_key = $this->model->getKeyName();
        $id = $request->post($primary_key);
        $data = $this->inputFilter($data);
        if (!Auth::isSupperAdmin() && $this->dataLimit && !empty($data[$this->dataLimitField])) {
            $admin_id = $data[$this->dataLimitField];
            if (!in_array($admin_id, Auth::getScopeAdminIds(true))) {
                throw new BusinessException('无数据权限');
            }
        }
        $password_filed = 'password';
        if (isset($data[$password_filed])) {
            // 密码为空，则不更新密码
            if ($data[$password_filed] === '') {
                unset($data[$password_filed]);
            } else {
                $data[$password_filed] = Util::passwordHash($data[$password_filed]);
            }
        }

        unset($data[$primary_key]);
        return [$id, $data];
    }

    /**
     * 更新
     * @param Request $request
     * @return Response
     * @throws BusinessException
    */
    public function update(Request $request): Response
    {
        if ($request->method() === 'POST') {
            return parent::update($request);
        }

        $id = $request->get('id');
        $store = Store::find($id)->toArray();
        $content = json_decode($store['content'], true);
        $content = $content ?? [];
        $firstContent = array_shift($content);
        return view('store/update', [
            'content' => $content,
            'firstContent' => $firstContent
        ]);
    }

    protected function formatNormal($items, $total): Response
    {
        $categories = StoreCategory::list();
        $categories = array_combine(
            array_column($categories, 'value'),
            array_column($categories, 'name')
        );

        foreach ($items as $key=>$item) {
            $items[$key]['category_name'] = $categories[$item['category_id']] ?? '';
        }

        return json(['code' => 0, 'msg' => 'ok', 'count' => $total, 'data' => $items]);
    }
}
